package chd.edu.spzx.manager.service.impl;

import chd.edu.spzx.common.exception.GuiguException;
import chd.edu.spzx.manager.listener.ExcelListener;
import chd.edu.spzx.manager.mapper.CategoryMapper;
import chd.edu.spzx.manager.service.CategoryService;
import chd.edu.spzx.model.entity.product.Category;
import chd.edu.spzx.model.vo.common.ResultCodeEnum;
import chd.edu.spzx.model.vo.product.CategoryExcelVo;
import com.alibaba.excel.EasyExcel;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Zhang Chaoliang
 * create 2023
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper ;

    /**
     * 分类列表--每次查询一层数据
     * @param id
     * @return
     */
    @Override
    public List<Category> findCategoryList(Long id) {
        //1. 根据id查询直接字分类，返回list集合
        List<Category> categoryList = categoryMapper.selectCategoryByParentId(id);

        //2. 遍历返回的list集合
        //判断每一个分类是否有下一层，如果有设置参数hasChildren = true
        if (!CollectionUtils.isEmpty(categoryList)){
            categoryList.forEach(category -> {
                //判断每一个分类是否有下一层
                int count = categoryMapper.selectCountByParentId(category.getId());
                if (count > 0){  //有下一层分类
                    category.setHasChildren(true);
                }else {
                    category.setHasChildren(false);
                }
            });
        }
        return categoryList;
    }

    /**
     * 导出分类列表
     * @param response
     */
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //1. 设置响应头信息和其他信息
            //  设置响应结果类型
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            //   这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("分类数据", "UTF-8");
            //   设置响应头信息
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            //2. 调用mapper方法查询所有的分类，返回list集合
            List<Category> categoryList = categoryMapper.findAll();
            // 将从数据库中查询到的Category对象转换成CategoryExcelVo对象
            List<CategoryExcelVo> categoryExcelVoList = new ArrayList<>(categoryList.size());
            for(Category category : categoryList) {
                CategoryExcelVo categoryExcelVo = new CategoryExcelVo();
                //把category中的值获取到然后赋值到categoryExcelVo中
                BeanUtils.copyProperties(category, categoryExcelVo);
                categoryExcelVoList.add(categoryExcelVo);
            }

            //3. 调用EasyExcel的write方法完成写操作
            EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class)
                    .sheet("分类数据").doWrite(categoryExcelVoList);
        }catch (Exception e){
            e.printStackTrace();
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
    }

    /**
     * 导入分类列表
     * @param file
     * @return
     */
    @Override
    public void importData(MultipartFile file) {
        try {
            //创建监听器对象，传递mapper对象
            ExcelListener<CategoryExcelVo> excelListener = new ExcelListener<>(categoryMapper);

            //调用read方法读取excel数据
            EasyExcel.read(file.getInputStream(), CategoryExcelVo.class,excelListener)
                    .sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
    }
}
